package com.wx.zwxs.controller;

import com.alibaba.fastjson.JSON;
import com.wx.zwxs.model.InMsgEntity;
import com.wx.zwxs.model.OutMsgEntity;
import com.wx.zwxs.model.WxAccess;
import com.wx.zwxs.service.WxService;
import com.wx.zwxs.util.WeiXinSignUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;


/**
 *
 * @Description: 微信请求处理的核心类
 * @Parameters:
 * @Return:
 * @Create Date:
 * @Version: V1.00
 * @author: 来日可期
 */
@RestController
@Slf4j
public class WeixinCoreController {
@Autowired
private WxService wxService;

    @Autowired
    private WeiXinSignUtil weixinSignUtil;
    /**
     * @Description: 验证请求是否来自微信服务器
     * @Parameters: WeixinCoreController
     * @Return: 返回微信服务器发过来的验证字符
     * @Create Date:
     * @Version: V1.00
     * @author:来日可期
     */
    @GetMapping("/access")
    public String WeChatInterface(HttpServletRequest request, WxAccess wxAccess)throws Exception {
        log.info(JSON.toJSONString(wxAccess));
        // 微信加密签名
        String signature = request.getParameter("signature");
        // 时间戳
        String timestamp = request.getParameter("timestamp");
        // 随机数
        String nonce = request.getParameter("nonce");
        // 随机字符串
        String echostr = request.getParameter("echostr");

        log.info(String.format("signature is :%s, timestamp is%s, nonce is :%s", signature, timestamp, nonce));

        if (weixinSignUtil.checkSignature(signature, timestamp, nonce)) {
            return echostr;
        } else {
            // 此处可以实现其他逻辑
            log.warn("不是微信服务器发过来的请求，请小心！");
            return echostr;
        }
    }

    @PostMapping(value = "/access",produces={"application/xml; charset=UTF-8"})
    public Object handleR(@RequestBody InMsgEntity msg){
        log.info("接收到微信端发送来的消息为：{}",JSON.toJSONString(msg));

        //创建消息响应对象
        OutMsgEntity out = new OutMsgEntity();
        //把原来的发送方设置为接收方
        out.setToUserName(msg.getFromUserName());
        //把原来的接收方设置为发送方
        out.setFromUserName(msg.getToUserName());
        //获取接收的消息类型
        String msgType = msg.getMsgType();
        //设置消息的响应类型
        out.setMsgType(msgType);
        //设置消息创建时间
        out.setCreateTime(new Date().getTime());
        //根据类型设置不同的消息数据
        if("text".equals(msgType)){
            out.setContent(msg.getContent());
        }else if("image".equals(msgType)){
            out.setMediaId(new String[]{msg.getMediaId()});
        }
        return out;
    }


    @GetMapping("/token")
    public String get(){
        return wxService.getAccessToken();
    }
}
